import React, { useState } from 'react';
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  StyleSheet,
  KeyboardAvoidingView,
  Platform,
  Image,
  Modal,
  Linking,
} from 'react-native';
import { Toast, Button } from '@ant-design/react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { request, setToken } from '../services/request';
import { setBaseUrl, getBaseUrl } from '../services/request';
import shezhi from '../assets/shezhi.png';
import bmk from '../assets/bmkaps.jpg';

interface LoginScreenProps {
  onLoginSuccess: () => void;
}

const LoginScreen: React.FC<LoginScreenProps> = ({ onLoginSuccess }) => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [settingsVisible, setSettingsVisible] = useState(false);
  const [settingsInput, setSettingsInput] = useState('');
  const [updateModalVisible, setUpdateModalVisible] = useState(false);
  const [updatePackageLink, setUpdatePackageLink] = useState('');
  const [updatePackageState, setUpdatePackageState] = useState<number>(1); // 更新状态：1不更新，2强制更新，3可选更新

  const handleLogin = async () => {
    if (username.trim() && password.trim()) {
      try {
        const res = await request('/app/auth/login', {
          method: 'POST',
          body: JSON.stringify({ num: username, password }),
        });
        console.log('登录接口返回:', res);
        if (res && res.code === 200) {
          if (res.data && res.data.token) {
            await setToken(res.data.token);
          }

          // 保存用户信息到AsyncStorage
          if (res.data) {
            await AsyncStorage.setItem('userInfo', JSON.stringify(res.data));
            console.log('保存用户信息:', res.data);
          }

          // 检查是否有应用更新
          // update_package_state: 1-不更新 2-强制更新 3-可选更新
          const updateState = res.data?.update_package_state;
          if (updateState && res.data?.package_link) {
            // 如果状态不为1（不需要更新），则显示更新弹窗
            if (updateState !== 1) {
              setUpdatePackageLink(res.data.package_link);
              setUpdatePackageState(updateState);
              setUpdateModalVisible(true);
            } else {
              // 状态为1，不更新，直接登录
              Toast.success(res.msg, 1);
              setTimeout(() => {
                onLoginSuccess();
              }, 500);
            }
          } else {
            Toast.success(res.msg, 1);
            setTimeout(() => {
              onLoginSuccess();
            }, 500);
          }
        } else {
          Toast.fail(res.msg || '用户名或密码错误', 1);
        }
      } catch (e: any) {
        Toast.fail(e.message || '网络错误', 1);
      }
    } else {
      Toast.info('请输入用户名和密码', 1);
    }
  };

  const handleSettingsPress = async () => {
    try {
      const currentUrl = await getBaseUrl();
      // 移除末尾的 /api/ 以便用户编辑
      const displayUrl = currentUrl.replace(/\/api\/$/, '');
      setSettingsInput(displayUrl);
      setSettingsVisible(true);
    } catch (error) {
      console.log('获取当前服务器地址失败:', error);
      setSettingsVisible(true);
    }
  };

  const handleSettingsConfirm = async () => {
    if (!settingsInput.trim()) {
      Toast.info('请输入服务器地址', 1);
      return;
    }
    try {
      await setBaseUrl(settingsInput.trim());
      Toast.success('服务器地址已保存', 1);
      setSettingsVisible(false);
      setSettingsInput('');
    } catch (error) {
      Toast.fail('保存失败，请重试', 1);
    }
  };

  const handleSettingsCancel = () => {
    setSettingsVisible(false);
    setSettingsInput('');
  };

  const handleUpdateConfirm = async () => {
    try {
      // 打开更新链接
      await Linking.openURL(updatePackageLink);
      // 如果是强制更新，关闭弹窗后不继续登录流程
      if (updatePackageState === 2) {
        setUpdateModalVisible(false);
        setUpdatePackageLink('');
        setUpdatePackageState(1);
      } else {
        // 如果是可选更新，更新后可以继续登录
        setUpdateModalVisible(false);
        setUpdatePackageLink('');
        setUpdatePackageState(1);
        Toast.success('登录成功', 1);
        setTimeout(() => {
          onLoginSuccess();
        }, 500);
      }
    } catch (error) {
      Toast.fail('无法打开更新链接', 1);
    }
  };

  const handleUpdateCancel = () => {
    setUpdateModalVisible(false);
    setUpdatePackageLink('');
    setUpdatePackageState(1);
    // 用户选择不更新，继续登录流程（仅在可选更新时可用）
    Toast.success('登录成功', 1);
    setTimeout(() => {
      onLoginSuccess();
    }, 500);
  };

  return (
    <KeyboardAvoidingView
      style={styles.container}
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
    >
      {/* 右上角设置按钮 */}
      <TouchableOpacity style={styles.settingsButton} onPress={handleSettingsPress}>
        <Image source={shezhi} style={styles.settingsIcon} />
      </TouchableOpacity>

      <View style={styles.content}>
        <Image source={bmk} style={styles.logo} />
        <Text style={styles.title}>宝玛克APS报工系统</Text>

        <View style={styles.inputContainer}>
          <View style={styles.inputWrapper}>
            <View style={styles.inputRow}>
              <TextInput
                style={styles.input}
                placeholder="请输入用户名"
                value={username}
                onChangeText={setUsername}
                autoCapitalize="none"
                placeholderTextColor="#999"
              />
              {username.length > 0 && (
                <TouchableOpacity
                  style={styles.clearButton}
                  onPress={() => setUsername('')}
                >
                  <Text style={styles.clearButtonText}>×</Text>
                </TouchableOpacity>
              )}
            </View>
          </View>

          <View style={styles.inputWrapper}>
            <View style={styles.inputRow}>
              <TextInput
                style={styles.input}
                placeholder="请输入密码"
                placeholderTextColor="#999"
                value={password}
                onChangeText={setPassword}
                secureTextEntry
                autoCapitalize="none"
              />
              {password.length > 0 && (
                <TouchableOpacity
                  style={styles.clearButton}
                  onPress={() => setPassword('')}
                >
                  <Text style={styles.clearButtonText}>×</Text>
                </TouchableOpacity>
              )}
            </View>
          </View>
        </View>

        <Button
          style={styles.loginButton}
          onPress={handleLogin}
          type="primary"
          size="large"
        >
          登录
        </Button>
      </View>

      {/* 设置弹出框 */}
      <Modal
        visible={settingsVisible}
        animationType="slide"
        transparent={true}
      >
        <View style={styles.modalContainer}>
          <View style={styles.modalContent}>
            <Text style={styles.modalTitle}>当前服务器地址</Text>
            <TextInput
              style={styles.modalInput}
              placeholder="请输入服务器地址"
              value={settingsInput}
              onChangeText={setSettingsInput}
              autoCapitalize="none"
              keyboardType="url"
            />
            <View style={styles.modalButtonContainer}>
              <Button
                style={styles.cancelButton}
                onPress={handleSettingsCancel}
              >
                取消
              </Button>
              <Button
                style={styles.modalButton}
                onPress={handleSettingsConfirm}
                type="primary"
              >
                确认
              </Button>
            </View>
          </View>
        </View>
      </Modal>

      {/* 应用更新弹窗 */}
      <Modal
        visible={updateModalVisible}
        animationType="slide"
        transparent={true}
      >
        <View style={styles.modalContainer}>
          <View style={styles.modalContent}>
            <Text style={styles.modalTitle}>应用更新</Text>
            <Text style={styles.updateMessage}>
              {updatePackageState === 2
                ? '检测到强制更新版本，请立即更新到最新版本！'
                : '检测到新版本可用，是否立即更新？'}
            </Text>
            <Text style={styles.updateLink}>
              更新链接：{updatePackageLink}
            </Text>
            <View style={styles.modalButtonContainer}>
              {/* 只有在可选更新时显示取消按钮 */}
              {updatePackageState === 3 && (
                <Button
                  style={styles.cancelButton}
                  onPress={handleUpdateCancel}
                >
                  稍后更新
                </Button>
              )}
              <Button
                style={styles.modalButton}
                onPress={handleUpdateConfirm}
                type="primary"
              >
                立即更新
              </Button>
            </View>
          </View>
        </View>
      </Modal>
    </KeyboardAvoidingView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  content: {
    flex: 1,
    justifyContent: 'center',
    paddingHorizontal: 30,
  },
  title: {
    fontSize: 28,
    fontWeight: 'bold',
    textAlign: 'center',
    marginBottom: 40,
    color: '#333',
  },
  inputContainer: {
    marginBottom: 30,
  },
  inputWrapper: {
    marginBottom: 15,
  },
  inputRow: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: 'white',
    borderRadius: 10,
    borderWidth: 1,
    borderColor: '#ddd',
  },
  input: {
    flex: 1,
    padding: 15,
    fontSize: 16,
  },
  clearButton: {
    padding: 15,
    justifyContent: 'center',
    alignItems: 'center',
  },
  clearButtonText: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#999',
    textAlign: 'center',
    width: 20,
    height: 20,
    lineHeight: 20,
  },
  loginButton: {
    borderRadius: 5,
    marginBottom: 15,
  },
  settingsButton: {
    position: 'absolute',
    top: 50,
    right: 20,
    padding: 8,
    zIndex: 10,
  },
  settingsIcon: {
    width: 24,
    height: 24,
  },
  modalContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
  },
  modalContent: {
    backgroundColor: 'white',
    padding: 20,
    borderRadius: 10,
    width: '80%',
    alignItems: 'center',
  },
  modalTitle: {
    fontSize: 20,
    fontWeight: 'bold',
    marginBottom: 20,
  },
  modalInput: {
    backgroundColor: 'white',
    borderRadius: 10,
    padding: 15,
    marginBottom: 20,
    borderWidth: 1,
    borderColor: '#ddd',
    width: '100%',
  },
  modalButtonContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    width: '100%',
    gap: 10,
    marginTop: 10,
  },
  modalButton: {
    flex: 1,
    marginLeft: 5,
  },
  cancelButton: {
    backgroundColor: '#f5f5f5',
    borderColor: '#ddd',
    borderWidth: 1,
    flex: 1,
    marginRight: 5,
  },
  logo: {
    width: 140,
    height: 140,
    alignSelf: 'center',
    marginBottom: 20,
  },
  updateMessage: {
    fontSize: 16,
    color: '#333',
    textAlign: 'center',
    marginBottom: 10,
  },
  updateLink: {
    fontSize: 14,
    color: '#007bff',
    textDecorationLine: 'underline',
    marginBottom: 20,
    textAlign: 'center',
  },
});

export default LoginScreen; 